#include "tcpsvr.hpp"
#include <vector>
#include <boost/algorithm/string.hpp>

int Add(std::string& Data)
{
    //1+1
    std::vector<std::string> output;
    boost::split(output, Data, boost::is_any_of("+"), boost::token_compress_off);
    int sum_num = 0;
    for(size_t i; i < output.size(); i++)
    {
        sum_num += atoi(output[i].c_str());
    }
    return sum_num;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        printf("./svr [ip] [port]\n");
        return 0;
    }

    std::string ip = argv[1];
    uint16_t port = atoi(argv[2]);

    TcpSvr ts;
    if(!ts.CreateSock())
    {
        return 0;
    }

    if(!ts.Bind(ip, port))
    {
        return 0;
    }

    if(!ts.Listen())
    {
        return 0;
    }
    TcpSvr peerts;
    struct sockaddr_in peeraddr;
    if(!ts.Accept(peerts, &peeraddr))
    {
        return 0;
    }
    printf("svr have a new connect, ip:port --> %s:%d\n", 
                inet_ntoa(peeraddr.sin_addr), ntohs(peeraddr.sin_port));

    while(1)
    {
        sleep(15);
        std::string buf;
        Data data;
        peerts.Recv(data);
        printf("client say:%d+%d\n", data.a, data.b);

        //1+1
        //int ret = Add(buf);
        //buf = std::to_string(ret);
        buf = std::to_string(data.a + data.b);
        peerts.Send(buf);
    }

    //peerts.Close();
    ts.Close();
    return 0;
}
